#拉取gitlab
DIR=$( dirname "$(readlink -f  ${BASH_SOURCE[0]})" )
PARENTPATH=$(dirname ${DIR})
ROOTPATH=$(dirname ${PARENTPATH})
source ${ROOTPATH}/tools.sh
sh ${PARENTPATH}/valid_docker_images.sh gitlab
if [ $? != "2" ]; then
   sudo docker pull gitlab/gitlab-ce
fi
if [ ! -d "/opt/soft/docker/gitlab" ];then
  sudo mkdir -p /opt/soft/docker/gitlab
fi
if [ -d "/opt/soft/docker/gitlab/config" ];then
  sudo chmod 644 /opt/soft/docker/gitlab/config/*
fi
if [[ $1 == 'force' ]]
then
  echo force
  docker stop gitlab
  docker rm gitlab
fi
declare -A updateKeyMap=(["external_url"]="'http:\/\/$(getIp)'" ["gitlab_rails\\['gitlab_ssh_host'\\]"]="'$(getIp)'")
updateKeyMap["gitlab_rails\\['gitlab_shell_ssh_port'\\]"]=222
rb_file_path="/opt/soft/docker/gitlab/config/gitlab.rb"
name=`uname -s`
flag=''
if [[ "${name}" = "Linux" ]]; then
  flag=''
else
  flag='" "'
fi
for key in ${!updateKeyMap[@]}
do
  source_line=`sudo cat ${rb_file_path} | grep -nE '^[ #]*'"${key}"'' | awk -F ':' '{print $1}'`
  source_content=`sudo cat ${rb_file_path} | grep -nE '^[ #]*'"${key}"'' | awk -F '[ =]+' '{print $NF}'`
  target_content="${updateKeyMap[$key]}"
  # target_content='ttt'
  echo ${source_line}
  echo ${source_content//\//\\/}
  echo $target_content
  sudo sed -i ${flag} ''"${source_line}"'s/'"${source_content//\//\\/}"'/'"${target_content}"'/' ${rb_file_path}
  sudo sed -i ${flag} ''"${source_line}"'s/\s*#\s*//' ${rb_file_path}
done
# sudo docker run -d  -p 443:443 -p 80:80 -p 222:22 --name gitlab --restart always --hostname 192.168.0.135 -e GITLAB_ROOT_PASSWORD="Qq15996779085" -v /opt/soft/docker/gitlab/config:/etc/gitlab -v /opt/soft/docker/gitlab/logs:/var/log/gitlab -v /opt/soft/docker/gitlab/data:/var/opt/gitlab gitlab/gitlab-ce
sed -i ${flag} 's/[0-9]\{3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/'"$(getIp)"'/g' ${PARENTPATH}/resource/gitlab.yml
docker-compose -f ${PARENTPATH}/resource/gitlab.yml up -d
passwordResult=`sudo docker exec -it gitlab grep 'Password:' /etc/gitlab/initial_root_password`
echo ${passwordResult}
# Download the binary for your system
sudo curl -L --output /usr/local/bin/gitlab-runner https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64

# Give it permission to execute
sudo chmod +x /usr/local/bin/gitlab-runner

# Create a GitLab Runner user
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash

# Install and run as a service
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start

